<template>
  <div class="qa-container" @click="isshow = false">
    <h2 style="text-align: center; margin-bottom: 30px">{{ headtitle }}</h2>
    <!-- 问题部分 -->
    <div class="question-section">
      <div class="aaaa"></div>
      <div>
        <div v-for="(item, index) in messages" :key="item">
          <div v-if="index % 2 == 0">
            <div class="question-header" v-for="sitem in item.content.atts" :key="sitem">
              <el-tooltip class="box-item" effect="dark" content="点击下载" placement="top">
                <h2 style="cursor: pointer" @click="download">
                  {{ sitem.name }} . {{ sitem.file_type }}
                </h2>
              </el-tooltip>
              <img src="../assets/logo1.png" alt="用户头像" class="avatar" />
            </div>
            <div class="aaaa"></div>
            <div class="question-header">
              <h2>{{ item.content.question }}</h2>
              <img src="../assets/logo1.png" alt="用户头像" class="avatar" />
            </div>
          </div>
          <div style="clear: both"></div>
          <!-- </div> -->

          <!-- 回答部分 -->
          <div class="answer-section" v-if="index % 2 != 0">
            <div class="answer-header">
              <img src="../assets/logo1.png" alt="AI头像" class="ai-avatar" />
              <div class="answer-content">
                <div class="answer-text">
                  <div>
                    <div class="markdown-body" v-html="item.response" v-if="item.showPd == false"></div>
                    <div class="flex items-center space-x-2" v-if="item.isload == true">
                      <div :class="`w-${size / 5} h-${size / 5
    } rounded-full bg-${color} bounce-dot`"></div>
                      <div :class="`w-${size / 5} h-${size / 5
    } rounded-full bg-${color} bounce-dot`"></div>
                      <div :class="`w-${size / 5} h-${size / 5
    } rounded-full bg-${color} bounce-dot`"></div>
                    </div>
                  </div>
                  <div v-if="item.showPd == true">
                    <div style="
                        font-family: Alibaba PuHuiTi 2, Alibaba PuHuiTi 20;
                        font-weight: 700;
                        font-size: 18px;
                        color: #333333;
                        line-height: 36px;
                        text-align: left;
                        font-style: normal;
                        text-transform: none;
                      ">
                      数据表格：
                    </div>
                    <el-table :data="JSON.parse(item.content.pdData)" :id="'table' + index" v-if="item.showPd == true"
                      style="margin-top: 10px" max-height="250">
                      <el-table-column v-for="sitem in item.content.tableHeaders" :key="sitem" :label="sitem"
                        width="auto" :property="sitem" show-overflow-tooltip />
                    </el-table>
                  </div>
                  <div>
                    <div v-if="item.showPd == true" style="
                        font-family: Alibaba PuHuiTi 2, Alibaba PuHuiTi 20;
                        font-weight: 700;
                        font-size: 18px;
                        color: #333333;
                        line-height: 36px;
                        text-align: left;
                        font-style: normal;
                        text-transform: none;
                        margin-top: 10px;
                      ">
                      数据图表：
                    </div>
                    <div :id="'textid' + index" style="margin-top: 10px" v-if="item.content.showChart == true"></div>
                  </div>

                  <div v-if="item.showSum == true" style="
                      font-family: Alibaba PuHuiTi 2, Alibaba PuHuiTi 20;
                      font-weight: 700;
                      font-size: 18px;
                      color: #333333;
                      line-height: 36px;
                      text-align: left;
                      font-style: normal;
                      text-transform: none;
                      margin-top: 10px;
                    ">
                    总结：
                    <div v-html="item.summary"></div>
                    <!-- {{ item.summary }} -->
                  </div>

                  <div v-if="item.att_list">
                    <el-tag v-for="(sitem, sindex) in item.att_list" :key="sindex" style="background: #fff !important">
                      <div style="color: #000">{{ sitem }}</div>
                    </el-tag>
                  </div>

                  <!-- <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="预览PPT"
                    placement="top"
                    v-if="item.ispptok == true"
                  > -->
                  <img v-if="item.ispptok == true || item.image" :src="'data:image/;base64,' + item.image" alt="" style="
                      width: 220px;
                      height: 124px;
                      border-radius: 12px;
                      border: 2px solid transparent;
                      transition: all 0.15s ease-in-out;
                      cursor: pointer;
                    " />
                  <!-- </el-tooltip> -->

                  <!-- 底部操作按钮 -->
                  <div v-if="item.isload == false" class="flex" style="margin-top: 10px">
                    <div>
                      <el-tooltip class="box-item" effect="dark" content="语音播报" placement="top"
                        v-if="item.isSpeaking == false">
                        <img src="../assets/24.png" alt="" style="width: 24px; height: 24px; cursor: pointer"
                          @click="broadcast(item)" />
                      </el-tooltip>
                      <el-tooltip class="box-item" effect="dark" content="暂停播报" placement="top"
                        v-if="item.isSpeaking == true && item.isPaused == false">
                        <img src="../assets/25.png" alt="" style="width: 24px; height: 24px; cursor: pointer"
                          @click="stopbroadcast(item)" />
                      </el-tooltip>
                      <el-tooltip class="box-item" effect="dark" content="继续播报" placement="top"
                        v-if="item.isPaused == true">
                        <img src="../assets/26.png" alt="" style="width: 24px; height: 24px; cursor: pointer"
                          @click="resume(item)" />
                      </el-tooltip>
                    </div>
                    <div style="margin-left: 20px" v-if="item.isPPT == true">
                      <el-button @click="Generate(item)"
                        v-if="item.ispptok == false && !item.content.rid">一键生成PPT</el-button>
                      <el-button @click="Downloadppt(item)"
                        v-if="item.ispptok == true || item.content.rid">下载PPT</el-button>
                      <!-- <el-button @click="Previewppt(item)" v-if="item.ispptok == true"
                        >预览PPT</el-button
                      > -->
                    </div>
                    <div style="margin-left: 20px" v-if="item.isWord == true">
                      <el-button @click="Generateword(item)" v-if="item.iswordok == false && !item.content.rid">一键生成WORD
                      </el-button>
                      <el-button @click="downloadWord(item)"
                        v-if="item.iswordok == true || item.content.rid">一键下载WORD</el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="chat-input">
      <div class="input-wrapper" :style="{ height: tags.length > 0 ? '271px' : '200px' }">
        <div style="position: absolute; z-index: 1000; top: 24px">
          <el-tag v-for="tag in tags" :key="tag.name" closable @close="handleClose(tag)">
            <div style="color: #000; margin-bottom: 5px">{{ tag.name }}</div>
            <div style="color: rgba(0, 0, 0, 0.3)">{{ tag.file_type }}</div>
          </el-tag>
        </div>
        <textarea class="textarea" type="text" v-model="qavalue" :style="{ top: tags.length > 0 ? '91px' : '24px' }"
          placeholder="随时@你想要的AI智能助手，使用各种能力..." @keydown.enter.prevent="handleEnter" />
        <div class="box" :style="{ marginTop: tags.length > 0 ? '191px' : '120px' }">
          <div class="flex">
            <el-select class="model-select" placeholder="选择模型" v-model="modelid">
              <el-option v-for="item in modelList" :key="item" :label="item" :value="item" />
            </el-select>
            <div class="action-buttons">
              <button :class="type == 0 ? 'btn-default' : 'btn-primary'" @click.stop="changetype(0)">
                <img src="../assets/4.png" alt="" v-if="type == 0" />
                <img v-if="type == 1" src="../assets/4-1.png" alt="" />数据库
              </button>
              <button :class="type == 1 ? 'btn-default' : 'btn-primary'" @click.stop="changetype(1)">
                <img src="../assets/5-1.png" alt="" v-if="type == 1" />
                <img v-if="type == 0" src="../assets/5.png" alt="" />知识库
              </button>
            </div>
          </div>
          <div class="tools">
            <el-tooltip class="box-item" effect="dark" content="常用语" placement="top">
              <div class="tools-item">
                <img v-if="!isshow" src="../assets/6.png" alt="" @click.stop="changeisshow" />
                <img v-else="isshow" src="../assets/6-1.png" alt="" @click.stop="changeisshow" />
                <div class="history-container" v-if="isshow">
                  <div class="history-header">
                    <h1>常用语</h1>
                  </div>

                  <div class="history-content">
                    <div v-for="item in historyData" :key="item.id" class="history-item"
                      @click.stop="selectuseful(item)">
                      <div class="flex-b">
                        <div>
                          <div class="item-content">
                            <div class="item-text">{{ item.content }}</div>
                          </div>
                        </div>

                        <div style="display: flex; align-items: center">
                          <!-- <div>
                          <img src="../assets/10.png" v-if="item.is_collected == false" alt=""
                            @click.stop.stop="handlefavorite(item)" />
                          <img src="../assets/10-1.png" v-else alt="" @click.stop.stop="handlefavorite(item)" />
                        </div> -->
                          <div>
                            <img src="../assets/11.png" v-if="item.isedit != true" alt=""
                              @click.stop.stop="handleedit(item)" />
                            <img src="../assets/11-1.png" v-else alt="" @click.stop.stop="handleedit(item)" />
                          </div>
                          <div>
                            <img src="../assets/12.png" @click.stop.stop="handleDelete(item)" v-if="item.isdel != true"
                              alt="" />
                            <img src="../assets/12-1.png" v-else alt="" />
                          </div>
                        </div>
                      </div>
                    </div>

                    <div class="addbox" @click.stop="addexpressions">＋ 添加常用语</div>
                  </div>
                </div>
              </div>
            </el-tooltip>
            <el-tooltip class="box-item" effect="dark" content="附件上传" placement="top">
              <el-upload :limit="3" ref="uploadFile" :action="uploadaction" :headers="headers" :file-list="filelist"
                multiple name="att" :show-file-list="false" :on-success="handlesuccess">
                <div class="tools-item">
                  <img src="../assets/7.png" alt="" />
                </div>
              </el-upload>
            </el-tooltip>

            <el-tooltip class="box-item" effect="dark" content="语音输入" placement="top">
              <div class="tools-item">
                <img src="../assets/8.png" alt="" @click="startSpeechRecognition" v-if="isListening == false" />
                <!-- 音量波形可视化 -->
                <div id="waveform" @click="stopSpeechRecognition" style="
                    width: 28px;
                    height: 40px;
                    align-items: center;
                    margin-left: 6px;
                    cursor: pointer;
                  " class="bottom-0 left-0 right-0 h-24 flex space-x-1 justify-center overflow-hidden"></div>
              </div>
            </el-tooltip>

            <el-tooltip class="box-item" effect="dark" content="发送" placement="top" v-if="isanswer == false">
              <div class="tools-item send">
                <img v-if="qavalue == '' || modelid == ''" src="../assets/9.png" alt="" style="cursor: no-drop"
                  @click.stop="sendmsg" />
                <img v-if="qavalue != '' && modelid != ''" src="../assets/9-1.png" alt="" @click.stop="sendmsg" />
              </div>
            </el-tooltip>

            <el-tooltip class="box-item" effect="dark" content="中止回答" placement="top" v-if="isanswer == true">
              <div class="tools-item send">
                <img src="../assets/23.png" alt="" style="width: 26px" @click.stop="stopanswer" />
              </div>
            </el-tooltip>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加常用语 -->
    <el-dialog v-model="dialogVisible" width="750">
      <div class="title1">{{ phrasetitle }}</div>
      <textarea class="textarea1" v-model="phrase" placeholder-style="color:#BCBEC0" placeholder="输入常用语内容... "
        @keydown.enter.prevent="handleEnter1"></textarea>
      <template #footer>
        <div class="footer">
          <div class="cancal" @click.stop="dialogVisible = false">取消</div>
          <div class="outok" @click.stop="addphrase">保存</div>
        </div>
      </template>
    </el-dialog>

    <!-- PPT选择 -->
    <div class="pptbox" v-if="dialogVisiblePPt">
      <div class="close" @click="close">
        <img src="../assets//27.png" alt="" style="width: 24px; height: 24px" />
      </div>
      <div class="pptselect">
        <div class="flex-b" style="width: 100%; height: 70px; border-bottom: 1px solid #e4e2e8">
          <div style="color: #141414; font-size: 22px; font-weight: 500">
            选择模板创建PPT
          </div>
          <el-button class="pptbtn" @click="handepptok">生成PPT</el-button>
        </div>
        <el-row :gutter="20">
          <el-col :span="6" v-for="(item, index) in pptList" :key="index" style="margin-top: 20px; cursor: pointer"
            @click="changeppt(item)">
            <img :src="'data:image/;base64,' + item.cover" alt="" :class="item.id == pptid ? 'pptborder' : ''" />
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import {
  computed,
  defineComponent,
  nextTick,
  onBeforeMount,
  reactive,
  toRefs,
  onMounted,
  onUnmounted,
  watch,
} from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import MarkdownIt from "markdown-it";
import "github-markdown-css/github-markdown.css";
import {
  getModels,
  getPhrasesList,
  Collected,
  addPhrases,
  delPhrases,
  getSessionsDes,
  creatSession,
  dialogue,
  audio2text,
  gettemplatesList,
  GeneratePPT,
  download_report,
  getreportbyid,
} from "../api/home.js";
import Plotly from "plotly.js-dist-min";
import axios from "axios";

export default defineComponent({
  name: "Home",
  setup() {
    const router = useRouter();
    const state = reactive({
      modelList: [],
      modelid: "",
      session: {},
      phrasetitle: "",
      messages: [],
      isshow: false,
      tags: [],
      type: 0,
      qavalue: "",
      dialogVisible: false,
      historyData: [],
      phrase: "",
      question: "中美贸易战对个人的影响是什么？",
      avatarUrl: "/logo.png",
      userInput: "",
      phraseid: "",
      interval: null,
      headtitle: "",
      questionid: "",
      chatid: "",
      uploadFile: null,
      uploadaction: "",
      recognition: null,
      isListening: false,
      headers: {
        Authorization: "Bearer " + localStorage.getItem("token"),
      },
      filelist: [],
      isanswer: false,
      audioChunks: [],
      audioURL: null,
      audioContext: null,
      analyser: null,
      microphone: null,
      dataArray: null,
      animationId: null,
      waveformBars: Array(30).fill(0),
      size: 60,
      color: "primary",
      xhr: null,
      isSpeaking: false,
      isPaused: false,
      voices: [],
      selectedVoice: "",
      animationFrameId: null,
      audioContext1: null,
      analyser1: null,
      volume: "",
      volume1: "",
      broadcastObj: {},
      pptList: [],
      pptid: "",
      dialogVisiblePPt: false,
      filetype: "",
      pptobj: {},
      wordobj: {},
      loading: null,
    });

    const changeisshow = () => {
      state.isshow = !state.isshow;
    };

    const addexpressions = () => {
      state.phrasetitle = "添加常用语";
      state.dialogVisible = true;
    };

    // 获取模型列表
    const getModelsList = async () => {
      const res = await getModels();
      if (res.code == 0) {
        state.modelList = res.data;
      } else {
        state.modelList = [];
      }
    };

    // 获取常用语列表
    const getphrasesList = async () => {
      const res = await getPhrasesList(0, 30);
      if (res.code == 0) {
        state.historyData = res.data.items;
      } else {
        state.historyData = [];
      }
    };

    // 添加取消收藏
    const handlefavorite = async (item) => {
      const res = await Collected(item.id);
      if (res.code == 0) {
        item.is_collected = !item.is_collected;
        ElMessage.success("操作成功");
      } else {
        ElMessage.error("操作失败");
      }
    };

    // 添加常用语
    const addphrase = async () => {
      if (state.phrase != "") {
        if (state.phraseid) {
          const res1 = await editPhrases(state.phraseid, {
            phrase: state.phrase,
            id: state.phraseid,
          });
          if (res1.code == 0) {
            ElMessage.success("操作成功");
            state.phrase = "";
            getphrasesList();
            state.dialogVisible = false;
          } else {
            ElMessage.error("操作失败");
          }
        } else {
          const res = await addPhrases({ phrase: state.phrase });
          if (res.code == 0) {
            ElMessage.success("操作成功");
            state.phrase = "";
            getphrasesList();
            state.dialogVisible = false;
          } else {
            ElMessage.error("操作失败");
          }
        }
      }
    };
    // 删除常用语
    const handleDelete = (item) => {
      item.isdel = true;
      ElMessageBox.confirm("确定要删除这条历史记录吗?", "删除", {
        confirmButtonText: "确定", // 确认按钮文本
        cancelButtonText: "取消", // 取消按钮文本
      })
        .then(async () => {
          const res = await delPhrases(item.id);
          if (res.code == 0) {
            state.historyData = state.historyData.filter((i) => i.id !== item.id);
            ElMessage.success("操作成功");
            getphrasesList();
          } else {
            ElMessage.error("操作失败");
          }
        })
        .catch(() => {
          item.isdel = false;
          // catch error
        });
    };

    // 开始语音录入
    const startSpeechRecognition = async () => {
      state.isListening = true;
      try {
        // 创建音频上下文
        if (!state.audioContext) {
          state.audioContext = new (window.AudioContext || window.webkitAudioContext)();
        }
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        state.recognition = new MediaRecorder(stream);
        state.recognition.ondataavailable = (e) => {
          state.audioChunks.push(e.data);
        };
        state.recognition.onstop = async () => {
          const audioBlob = new Blob(state.audioChunks);
          var url = ""
          if (import.meta.env.VITE_APP_BASE_API) {
            url = import.meta.env.VITE_APP_BASE_API + "/api/v0/audio2text"
          } else {
            url = "/api/v0/audio2text"
          }
          const res = await axios.post(url,
            audioBlob, {
            headers: {
              "Content-Type": "application/octet-stream",
              Authorization: `Bearer ` + localStorage.getItem("token"),
            },
          });
          if (res.data.code == 0) {
            state.audioChunks = [];
            state.qavalue = res.data.data;
          }
          state.audioURL = URL.createObjectURL(audioBlob);
          state.isListening = false; // Stop recording state change
        };
        state.recognition.start();
        state.analyser = state.audioContext.createAnalyser();
        state.analyser.fftSize = 256;
        const bufferLength = state.analyser.frequencyBinCount;
        state.dataArray = new Uint8Array(bufferLength);
        // 连接麦克风到分析器
        state.microphone = state.audioContext.createMediaStreamSource(stream);
        state.microphone.connect(state.analyser);

        // 开始分析声音
        analyzeSound();
      } catch (error) {
        state.isListening = false;
        console.error("Error accessing the microphone:", error);
      }
    };

    // 停止语音录入
    const stopSpeechRecognition = async () => {
      if (state.recognition) {
        state.isListening = false;
        state.recognition.stop();
      }
    };

    // 分析声音
    const analyzeSound = () => {
      if (!state.isListening) return;
      // 获取音频数据
      state.analyser.getByteFrequencyData(state.dataArray);
      // 计算平均音量
      let sum = 0;
      state.dataArray.forEach((value) => {
        sum += value;
      });
      // 标准化音量值 (0-1)
      const average = sum / state.dataArray.length;
      state.volume = Math.min(1, average / 255);
      // 更新波形数据
      state.waveformBars = state.waveformBars.map((_, index) => {
        // 为波形条创建平滑过渡效果
        const targetValue = state.dataArray[index * 8] / 255;
        return Math.max(0.1, Math.min(1, targetValue));
      });

      updateWaveform();
      // 继续分析
      state.animationId = requestAnimationFrame(() => analyzeSound());
    };

    // 初始化波形可视化
    const initWaveform = () => {
      const waveformContainer = document.getElementById("waveform");
      waveformContainer.innerHTML = "";
      for (let i = 0; i < 5; i++) {
        const bar = document.createElement("div");
        bar.className = "bg-primary/30 w-2 rounded-t-lg transition-all duration-100";
        bar.style.height = "20%";
        bar.dataset.index = i;
        waveformContainer.appendChild(bar);
      }
    };

    // 更新波形可视化
    const updateWaveform = () => {
      const bars = document.querySelectorAll("#waveform div");
      bars.forEach((bar, index) => {
        // 使用随机值创建自然波形效果
        const height = Math.max(15, state.waveformBars[index] * 100);
        bar.style.height = `${height}%`;
      });
    };

    // 重命名
    const handleedit = async (item) => {
      state.phrasetitle = "修改常用语";
      state.phraseid = item.id;
      state.phrase = item.content;
      state.dialogVisible = true;
    };

    // 停止回答
    const stopanswer = () => {
      state.isanswer = !state.isanswer;
      if (state.xhr) {
        state.xhr.abort();
      }
      localStorage.removeItem("tags");
      if (state.messages.length > 0) {
        state.messages[state.messages.length - 1].response += " 人为停止";
        state.messages[state.messages.length - 1].isload = false;
      }
      // clearInterval(state.interval);
    };

    // 发送消息
    const sendmsg = async () => {
      if (state.questionid == '') {
        Creat()
      }
      // clearInterval(state.interval);
      state.isanswer = !state.isanswer;
      if (state.qavalue == "") {
        ElMessage.error("请输入问题");
        return;
      }
      if (state.modelid == "") {
        ElMessage.error("请选择模型");
        return;
      }
      router.replace({
        query: {
          ...router.currentRoute.value.query,
          question: state.qavalue,
          id: state.chatid,
        },
      });
      // router.currentRoute.value.query.question = state.qavalue
      const data = {
        question: state.qavalue,
        sid: state.questionid,
        queryType: state.type,
        llm: state.modelid,
        atts: [],
      };
      var arr = [];
      var tags = JSON.parse(localStorage.getItem("tags"));
      var mesitem = {
        content: {
          atts: [],
          question: state.qavalue,
        },
        role: "user",
      };
      if (tags) {
        tags.forEach((item) => {
          arr.push(item.id);
          mesitem.content.atts.push({
            file_type: item.file_type,
            id: item.id,
            name: item.name,
          });
        });
      }
      data.atts = arr;
      state.messages.push(mesitem);
      state.messages.push({
        content: {
          chartData: "",
          id: "",
          pdData: "",
          response: "",
          showChart: false,
          showPd: false,
          showSum: false,
          summary: "",
          tableHeaders: [],
          isWord: false,
          isPPT: false,
        },
        isshow: false,
        showPd: false,
        showSum: false,
        showChart: false,
        isload: true,
        response: "",
        isWord: false,
        isPPT: false,
        isSpeaking: false,
        isPaused: false,
        ispptok: false,
        iswordok: false,
        pptobj: {},
        wordobj: {},
      });
      const md = MarkdownIt({
        html: true, // 允许HTML标签
        linkify: true, // 自动识别URL
        typographer: true, // 智能标点转换
      });
      state.xhr = new XMLHttpRequest();
      var url = ''
      if (import.meta.env.VITE_APP_BASE_API) {
        url = import.meta.env.VITE_APP_BASE_API + "/api/v0/stream"
      } else {
        url = "/api/v0/stream"
      }
      state.xhr.open("POST", url, true);
      state.xhr.setRequestHeader(
        "Authorization",
        "Bearer " + localStorage.getItem("token")
      );
      state.xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      state.xhr.withCredentials = true;
      // 监听数据加载事件
      state.xhr.onprogress = function () {
        // responseText包含已接收的全部数据
        const chunk = state.xhr.responseText.substring(
          state.xhr.responseText.length - state.xhr.getResponseHeader("Content-Length")
        );
        state.messages[state.messages.length - 1].response = state.xhr.responseText;
        state.messages[state.messages.length - 1].response = md.render(
          state.messages[state.messages.length - 1].response
        );
        // state.messages[state.messages.length - 1].response = state.xhr.responseText;
        // state.messages[state.messages.length - 1].response = state.messages[
        //   state.messages.length - 1
        // ].response.replace(/\n/gm, "<br/>");
        // 处理数据块
        // updateUI(chunk);
      };

      state.xhr.onload = async () => {
        if (state.xhr.status === 200) {
          state.isanswer = !state.isanswer;
          const rest = await dialogue({ sid: state.questionid });
          if (rest.code == 0) {
            router.replace({
              query: {
                ...router.currentRoute.value.query,
                question: state.qavalue + '.',
              },
            });
            state.session = rest.data.session;
            state.headtitle = rest.data.session.name;
            state.messages[state.messages.length - 1].content = rest.data.message;
            setTimeout(() => {
              // if (state.messages[state.messages.length - 1].content.isPPT == true || state.messages[state.messages.length - 1].content.isWord == true) {
              state.messages[state.messages.length - 1].response = md.render(state.messages[state.messages.length - 1].content.response)
              // }
              state.messages[state.messages.length - 1].showPd =
                state.messages[state.messages.length - 1].content.showPd;
              state.messages[state.messages.length - 1].showSum =
                state.messages[state.messages.length - 1].content.showSum;
              state.messages[state.messages.length - 1].showChart =
                state.messages[state.messages.length - 1].content.showChart;
              state.messages[state.messages.length - 1].isload = false;
              state.messages[state.messages.length - 1].isWord =
                state.messages[state.messages.length - 1].content.isWord;
              state.messages[state.messages.length - 1].isPPT =
                state.messages[state.messages.length - 1].content.isPPT;
              state.messages[state.messages.length - 1].summary =
                state.messages[state.messages.length - 1].content.summary;
              if (state.messages[state.messages.length - 1].summary) {
                state.messages[state.messages.length - 1].summary = md.render(
                  state.messages[state.messages.length - 1].summary
                );
              }
              var str = "textid" + (state.messages.length - 1);
              if (state.messages[state.messages.length - 1].content.showChart == true) {
                Plotly.newPlot(
                  str,
                  JSON.parse(state.messages[state.messages.length - 1].content.chartData)
                    .data,
                  JSON.parse(state.messages[state.messages.length - 1].content.chartData)
                    .layout
                );
              }
              // state.isanswer = !state.isanswer;
            }, 1000);
          } else {
            ElMessage.error(rest.msg);
            if (state.messages.length > 0) {
              state.messages[state.messages.length - 1].response += " 接口错误";
              state.messages[state.messages.length - 1].isload = false;
            }
          }
          localStorage.removeItem("tags");
          console.log("全部数据接收完成");
        } else {

          state.isanswer = !state.isanswer;
          console.error("请求失败:", state.xhr.status);
        }
      };

      state.xhr.send(JSON.stringify(data));
      state.qavalue = "";
    };

    watch(
      () => router.currentRoute.value.query.question,
      () => {
        // clearInterval(state.interval);
        if (router.currentRoute.value.query.question == undefined) {
          // state.modelid = "";
          state.questionid = "";
          state.messages = [];
          state.session = {};
          state.qavalue = "";
          // Creat();
        }
      }
    );

    watch(
      () => router.currentRoute.value.query.id,
      async () => {
        state.broadcastObj = {}
         window.speechSynthesis.pause();
        state.chatid = router.currentRoute.value.query.id;
        state.isanswer = true;
        const md = MarkdownIt({
          html: true, // 允许HTML标签
          linkify: true, // 自动识别URL
          typographer: true, // 智能标点转换
        });
        const res = await getSessionsDes(state.chatid);
        if (res.code == 0) {
          // console.log(res);
          state.headtitle = res.data.session.name;
          state.messages = res.data.messages;
          state.messages.forEach(async (item, index) => {
            state.messages[index].isshow = false;
            state.messages[index].showPd = false;
            state.messages[index].showSum = false;
            state.messages[index].showChart = false;
            state.messages[index].isload = true;
            state.messages[index].isWord = false;
            state.messages[index].isPPT = false;
            state.messages[index].isSpeaking = false;
            state.messages[index].isPaused = false;
            state.messages[index].ispptok = false;
            state.messages[index].iswordok = false;
            state.messages[index].pptobj = {};
            state.messages[index].wordobj = {};
            // if (item.content.rid) {
            //   var rest = await getreportbyid(item.content.rid)
            //   if (rest.code == 0) {
            //     item.cover = rest.data.cover
            //   }
            // }
            if (index % 2 != 0) {
              // var index1 = 0;
              item.response = "";
              // state.messages[index].response += item.content.response[index1];
              state.messages[index].response = state.messages[index].content.response;
              // index1++;
              // state.messages[index].response = item.response;
              state.messages[index].response = md.render(state.messages[index].response);
              // state.messages[state.messages.length - 1].response = md.render(
              //   state.xhr.responseText
              // );
              var str = "textid" + index;
              setTimeout(() => {
                // if (item.content.isPPT == true || item.content.isWord == true) {
                const md = MarkdownIt({
                  html: true, // 允许HTML标签
                  linkify: true, // 自动识别URL
                  typographer: true, // 智能标点转换
                });
                state.messages[index].response = md.render(
                  state.messages[index].response
                );
                // }
                state.messages[index].isshow = true;
                state.messages[index].showPd = item.content.showPd;
                state.messages[index].showSum = item.content.showSum;
                state.messages[index].showChart = item.content.showChart;
                state.messages[index].isload = false;
                state.messages[index].isWord = item.content.isWord;
                state.messages[index].isPPT = item.content.isPPT;
                state.messages[index].summary = item.content.summary;
                if (state.messages[index].summary) {
                  state.messages[index].summary = md.render(
                    state.messages[index].summary
                  );
                }
                if (item.content.showChart == true) {
                  Plotly.newPlot(
                    str,
                    JSON.parse(item.content.chartData).data,
                    JSON.parse(item.content.chartData).layout
                  );
                }
              }, 300);
            }
          });
          state.isanswer = !state.isanswer;
          if (res.data.session.chosen_model) {
            state.modelid = res.data.session.chosen_model;
          }
          state.session = res.data.session;
        } else {
          state.isanswer = !state.isanswer;
        }
      }
    );

    onMounted(async () => {
      if (import.meta.env.VITE_APP_BASE_API) {
        state.uploadaction = import.meta.env.VITE_APP_BASE_API + "/api/v0/attachment";
      } else {
        state.uploadaction = "/api/v0/attachment";
      }
      getPptList();
      initWaveform();
      loadVoices();
      if (router.currentRoute.value.query.modelid) {
        state.modelid = router.currentRoute.value.query.modelid;
      }
      state.chatid = router.currentRoute.value.query.id;
      getModelsList();
      getphrasesList();
      // if (router.currentRoute.value.query.question) {
      state.isanswer = !state.isanswer;
      const res = await getSessionsDes(state.chatid);
      // console.log(res); 
      if (res.code == 0) {
        state.headtitle = res.data.session.name;
        state.messages = res.data.messages;
        const md = MarkdownIt({
          html: true, // 允许HTML标签
          linkify: true, // 自动识别URL
          typographer: true, // 智能标点转换
        });
        state.messages.forEach(async (item, index) => {
          state.messages[index].isshow = false;
          state.messages[index].showPd = false;
          state.messages[index].showSum = false;
          state.messages[index].showChart = false;
          state.messages[index].isload = true;
          state.messages[index].isWord = false;
          state.messages[index].isPPT = false;
          state.messages[index].isSpeaking = false;
          state.messages[index].isPaused = false;
          state.messages[index].ispptok = false;
          state.messages[index].iswordok = false;
          state.messages[index].pptobj = {};
          state.messages[index].wordobj = {};
          // if (item.content.rid) {
          //   var rest = await getreportbyid(item.content.rid)
          //   if (rest.code == 0) {
          //     item.cover = rest.data.cover
          //   }
          // }
          if (index % 2 != 0) {
            // var index1 = 0;
            item.response = "";
            // state.messages[index].response += item.content.response[index1];
            state.messages[index].response = state.messages[index].content.response;
            // state.messages[index].response = state.messages[index].content.response.replace(
            //   /\n/gm,
            //   "<br/>"
            // );
            // index1++;
            // state.messages[index].response = item.response;
            state.messages[index].response = md.render(state.messages[index].response);
            var str = "textid" + index;
            setTimeout(() => {
              // if (item.content.isPPT == true || item.content.isWord == true) {
              const md = MarkdownIt({
                html: true, // 允许HTML标签
                // xhtmlOut: false, // 使用HTML5标签
                // breaks: true, // 转换换行符为<br>
                // langPrefix: "language-", // 代码块语言前缀
                linkify: true, // 自动识别URL
                typographer: true, // 智能标点转换
              });
              state.messages[index].response = md.render(state.messages[index].response);
              // }

              state.messages[index].isshow = true;
              state.messages[index].showPd = item.content.showPd;
              state.messages[index].showSum = item.content.showSum;
              state.messages[index].showChart = item.content.showChart;
              state.messages[index].isload = false;
              state.messages[index].isWord = item.content.isWord;
              state.messages[index].isPPT = item.content.isPPT;
              state.messages[index].summary = item.content.summary;
              if (state.messages[index].summary) {
                state.messages[index].summary = md.render(
                  state.messages[index].summary
                );
              }
              if (item.content.showChart == true) {
                Plotly.newPlot(
                  str,
                  JSON.parse(item.content.chartData).data,
                  JSON.parse(item.content.chartData).layout
                );
              }

            }, 300);
          }
        });
        if (res.data.session.chosen_model) {
          state.modelid = res.data.session.chosen_model;
        }
        state.isanswer = !state.isanswer;
        state.session = res.data.session;
        state.questionid = res.data.session.id;
      } else {
        state.isanswer = !state.isanswer;
      }
      // }
    });

    const Creat = async () => {
      const res = await creatSession({ name: router.currentRoute.value.query.question });
      if (res.code == 0) {
        state.headtitle = res.data.name;
        state.questionid = res.data.id;
      }
    };

    // 上传附件
    const handlesuccess = (res) => {
      if (res.code == 0) {
        var arr = [];
        if (state.tags) {
          arr = state.tags;
        }
        arr.push({ name: res.data.name, id: res.data.id, file_type: res.data.file_type });
        state.tags = arr;
        localStorage.setItem("tags", JSON.stringify(state.tags));
      } else {
        state["uploadFile"].uploadFiles.splice(
          state["uploadFile"].uploadFiles.length - 1,
          1
        );
      }
    };

    const handleEnter = (e) => {
      if (e.isComposing == false) {
        if (e.shiftKey) {
          // 如果按下 Shift + Enter，添加换行符
          state.qavalue += "\n";
        } else {
          // 如果只按下 Enter，触发发送
          if (state.isanswer == true) {
          } else {
            sendmsg();
          }
        }
      } else {
        if (e.shiftKey) {
          // 如果按下 Shift + Enter，添加换行符
          state.qavalue += "\n";
        }
      }
    };

    const selectuseful = (item) => {
      state.qavalue = item.content;
    };

    onUnmounted(() => {
      // clearInterval(state.interval);
      stopanswer();
      window.speechSynthesis.pause();
    });

    const handleEnter1 = (e) => {
      if (e.isComposing == false) {
        if (e.shiftKey) {
          // 如果按下 Shift + Enter，添加换行符
          state.phrase += "\n";
        } else {
          // 如果只按下 Enter，触发发送
          addphrase();
        }
      } else {
        if (e.shiftKey) {
          // 如果按下 Shift + Enter，添加换行符
          state.phrase += "\n";
        }
      }
    };

    const handleClose = (tag) => {
      state.tags.splice(state.tags.indexOf(tag), 1);
      var arr = JSON.parse(localStorage.getItem("tags"));
      arr.splice(arr.indexOf(tag), 1);
      if (arr.length != 0) {
        localStorage.setItem("tags", JSON.stringify(arr));
      } else {
        localStorage.removeItem("tags");
      }
    };

    // 语音播报
    const broadcast = (item) => {
      if (state.broadcastObj) {
        state.broadcastObj.isSpeaking = false;
        state.broadcastObj.isPaused = false;
      }
      state.broadcastObj = item;
      var text;
      if (item.showSum == true) {
        text = item.content.summary;
      } else {
        text = item.response;
      }

      // if (!text.trim() || item.isSpeaking) return;

      // 取消当前可能正在进行的语音
      window.speechSynthesis.cancel();

      const utterance = new SpeechSynthesisUtterance(text);

      // 设置语音
      const voice = state.voices.find((v) => v.name === state.selectedVoice);
      if (voice) utterance.voice = voice;

      // 设置语速
      utterance.rate = 1;

      // 设置事件监听
      utterance.onstart = () => {
        item.isSpeaking = true;
        item.isPaused = false;
      };

      utterance.onend = () => {
        item.isSpeaking = false;
        item.isPaused = false;
      };

      utterance.onpause = () => {
        item.isPaused = true;
      };

      utterance.onresume = () => {
        item.isPaused = false;
      };
      // 开始朗读
      window.speechSynthesis.speak(utterance);
    };

    // 获取支持的语音列表
    const loadVoices = () => {
      state.voices = window.speechSynthesis.getVoices();
      // 设置默认语音
      if (state.voices.length > 0) {
        // 优先选择中文语音
        const chineseVoice = state.voices.find((voice) => voice.lang.includes("zh"));
        state.selectedVoice = chineseVoice ? chineseVoice.name : state.voices[0].name;
      }
    };

    // 暂停播报
    const stopbroadcast = (item) => {
      if (item.isSpeaking && !item.isPaused) {
        window.speechSynthesis.pause();
      }
    };

    // 继续朗读
    const resume = (item) => {
      if (item.content.id == state.broadcastObj.content.id) {
        if (item.isSpeaking && item.isPaused) {
          window.speechSynthesis.resume();
        }
      } else {
        broadcast(item);
      }
    };

    // 点击生成PPT打开弹框
    const Generate = (item) => {
      state.pptobj = item;
      item.pptobj = JSON.parse(JSON.stringify(item));
      state.dialogVisiblePPt = true;
      item.filetype = "ppt";
    };

    // 一键生成word
    const Generateword = async (item) => {
      state.wordobj = item;
      item.wordobj = JSON.parse(JSON.stringify(item));
      item.filetype = "word";
      var data = {
        mid: state.wordobj.content.id,
        type: state.wordobj.filetype,
      };
      state.loading = ElLoading.service({
        lock: true,
        text: "正在努力生成中。。。",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const res = await GeneratePPT(data);
      if (res.code == 0) {
        state.loading.close();
        state.wordobj.wordobj = res.data;
        state.wordobj.iswordok = true;
        close();
      }
    };

    // 取消弹框
    const close = () => {
      state.dialogVisiblePPt = false;
    };

    // 获取ppt模版列表
    const getPptList = async () => {
      const res = await gettemplatesList(0, 50);
      if (res.code == 0) {
        state.pptList = res.data.items;
      } else {
        state.pptList = [];
      }
    };

    // 切换ppt模版
    const changeppt = (item) => {
      state.pptid = item.id;
      state.pptobj.image = item.cover;
    };

    // 确定生成ppt
    const handepptok = async () => {
      if (state.pptid != "") {
        state.loading = ElLoading.service({
          lock: true,
          text: "正在努力生成中。。。",
          background: "rgba(0, 0, 0, 0.7)",
        });
        var data = {
          mid: state.pptobj.content.id,
          type: state.pptobj.filetype,
          tid: state.pptid,
        };
        const res = await GeneratePPT(data);
        if (res.code == 0) {
          state.loading.close();
          state.pptobj.pptobj = res.data;
          state.pptobj.pptid = state.pptid;
          state.pptobj.ispptok = true;
          state.pptid == "";
          close();
        }
      } else {
        ElMessage.error("请选择模板");
      }
    };

    // 下载ppt
    const Downloadppt = async (item) => {
      var id = "";
      if (item.content.rid) {
        id = item.content.rif;
      } else {
        id = item.pptobj.id;
      }
      var url = "/api/v0/download_report/" + id;
      window.open(url, "_blank");
      // let currentDate = new Date();
      // let year = currentDate.getFullYear(); // 获取当前年份
      // let month = currentDate.getMonth() + 1; // 获取当前月份，注意月份从0开始，所以要加1
      // let day = currentDate.getDate();
      // const res = await download_report(id);
      // const blob = new Blob([res]); //创建一个blob对象
      // const a = document.createElement("a"); //创建一个标签
      // a.href = URL.createObjectURL(blob); // response is a blob
      // a.download = item.pptobj.name + ".ppt"; //文件名称
      // a.style.display = "none";
      // document.body.appendChild(a);
      // a.click();
      // a.remove();
    };

    const downloadWord = async (item) => {
      var id = "";
      if (item.content.rid) {
        id = item.content.rif;
      } else {
        id = item.wordobj.id;
      }
      var url = "/api/v0/download_report/" + id;
      window.open(url, "_blank");
      // let currentDate = new Date();
      // let year = currentDate.getFullYear(); // 获取当前年份
      // let month = currentDate.getMonth() + 1; // 获取当前月份，注意月份从0开始，所以要加1
      // let day = currentDate.getDate();
      // const res = await download_report(id);
      // const blob = new Blob([res]); //创建一个blob对象
      // const a = document.createElement("a"); //创建一个标签
      // a.href = URL.createObjectURL(blob); // response is a blob
      // a.download = item.wordobj.name+ ".word"; //文件名称
      // a.style.display = "none";
      // document.body.appendChild(a);
      // a.click();
      // a.remove();
    };

    // 预览ppt
    const Previewppt = (item) => {
      const url = "data:application/pdf;base64," + item.pptobj.report;
      window.open(url);
    };

    const changetype = (e) => {
      state.type = e;
    };

    return {
      ...toRefs(state),
      changeisshow,
      addexpressions,
      getModelsList,
      handlefavorite,
      getphrasesList,
      addphrase,
      handleDelete,
      handleedit,
      sendmsg,
      Creat,
      handlesuccess,
      startSpeechRecognition,
      stopSpeechRecognition,
      selectuseful,
      handleEnter,
      handleEnter1,
      handleClose,
      stopanswer,
      broadcast,
      loadVoices,
      stopbroadcast,
      resume,
      Generate,
      changeppt,
      getPptList,
      close,
      handepptok,
      Downloadppt,
      Previewppt,
      Generateword,
      downloadWord,
      changetype
    };
  },
});
</script>

<style scoped>
.markdown-body {
  background: transparent !important;
}

.markdown-container {
  line-height: 1.6;
  color: #333;
}

/* 自定义Markdown样式 */
.markdown-container h1,
h2,
h3 {
  margin-top: 1.5em;
  margin-bottom: 0.5em;
}

.markdown-container p {
  margin-bottom: 1em;
}

.markdown-container ul,
ol {
  padding-left: 2em;
  margin-bottom: 1em;
}

.markdown-container a {
  color: #0366d6;
  text-decoration: none;
}

.markdown-container a:hover {
  text-decoration: underline;
}

.markdown-container code {
  padding: 0.2em 0.4em;
  margin: 0;
  font-size: 85%;
  background-color: rgba(27, 31, 35, 0.05);
  border-radius: 3px;
}

.markdown-container pre {
  padding: 16px;
  overflow: auto;
  font-size: 85%;
  line-height: 1.45;
  background-color: #f6f8fa;
  border-radius: 3px;
}

.pptbox {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  background: #e5e5e5;
  z-index: 1000;
}

.pptborder {
  border-color: #256fff !important;
}

.close {
  position: absolute;
  z-index: 3;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  box-shadow: 0 0 16px 1px rgba(0, 0, 0, 0.12);
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
  cursor: pointer;
  top: 40px;
  left: 60px;
}

.pptselect {
  max-width: 1160px;
  width: 60%;
  position: absolute;
  top: 88px;
  bottom: 96px;
  left: 50%;
  transform: translate(-50%);
  background-color: #fff;
  border: 1px solid #e6e6e6;
  border-radius: 28px;
  overflow: hidden;
  animation: zoomIn-b7f1faee 0.3s cubic-bezier(0.075, 0.82, 0.165, 1);
  padding: 36px;
  box-sizing: border-box;
}

.pptselect img {
  width: 220px;
  height: 120px;
  border-radius: 12px;
  border: 2px solid transparent;
  transition: all 0.15s ease-in-out;
  margin: auto;
}

.pptbtn {
  height: 40px;
  padding: 0 24px;
  display: inline-flex;
  align-items: center;
  justify-content: flex-start;
  border: none;
  box-shadow: none;
  color: #fff;
  background: #256fff;
  border-radius: 4px;
  font-weight: 500;
  position: relative;
  transition: all 0.2s ease-in-out;
  font-size: 16px;
}

.qa-container {
  margin: 0 auto;
  padding: 30px 215px 230px 215px;
  text-align: left;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
    Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  width: 100%;
  height: calc(100vh);
  overflow: auto;
  overflow-y: scroll;
  /* scrollbar-width: none; */
  /* Firefox */
  /* -ms-overflow-style: none; */
  /* Internet Explorer 10+ */
  scrollbar-color: #dadada transparent;
}

:deep().el-tag {
  padding: 8px;
  height: auto;
  background: #f5f5f5 !important;
  text-align: left;
  margin-right: 10px;
}

.qa-container h2 {
  font-family: Source Han Sans, Source Han Sans;
  font-weight: 700;
  font-size: 24px;
  color: #3d3d3d;
  line-height: 35px;
  font-style: normal;
  text-transform: none;
  margin-top: 0 !important
    /* margin-bottom: 60px; */
}

.question-section {
  flex-direction: column-reverse;
  /* height: calc(100vh - 400px); */
  display: flex;

}

.question-header {
  display: flex;
  /* justify-content: space-between; */
  float: right;
  align-items: center;
  margin-right: -45px;
  /* margin-bottom: 60px; */
}

.question-header h2 {
  background: #fff;
  border-radius: 25px 25px 0 25px;
  display: block;
  padding: 17px 20px;
  font-weight: 700;
  font-size: 18px;
  color: #333333;
  line-height: 18px;
  text-align: left;
  font-style: normal;
  text-transform: none;
}

.avatar {
  width: 30px;
  height: 30px;
  margin-left: 15px;
  border-radius: 50%;
}

.ai-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 15px;
}

.answer-section {
  border-radius: 8px;
  margin-bottom: 30px;
  margin-top: 30px;
}

:deep().tools .el-tooltip__trigger {
  height: 40px !important;
}

.answer-header {
  display: flex;
  align-items: flex-start;
}

.answer-content {
  flex: 1;
  width: calc(100% - 180px) !important
}

.answer-text h3 {
  margin-top: 0;
  color: #333;
  font-size: 16px;
  line-height: 1.5;
}

.analysis h4 {
  margin-top: 15px;
  color: #333;
  font-size: 14px;
}

.analysis ul {
  margin: 10px 0;
  padding-left: 20px;
}

.analysis li {
  color: #666;
  margin-bottom: 8px;
  line-height: 1.6;
}

.input-section {
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 15px;
}

.input-container {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.input-field {
  flex: 1;
  padding: 8px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.button-group {
  display: flex;
  gap: 10px;
}

.action-button {
  padding: 8px 15px;
  background-color: #e8f0fe;
  border: none;
  border-radius: 4px;
  color: #1a73e8;
  cursor: pointer;
}

.action-icons {
  display: flex;
  gap: 15px;
}

.icon {
  cursor: pointer;
  font-size: 20px;
}

.textarea {
  position: absolute;
  top: 24px;
  left: 24px;
  border: 0;
  width: calc(100% - 48px);
  height: 100px;
  resize: none;
}

.addbox {
  position: absolute;
  bottom: 10px;
  width: calc(100% - 40px);
  border-radius: 20px;
  opacity: 1;
  border: 1px solid #bfdafe;
  line-height: 40px;
  color: #4e6bfe;
  font-size: 14px;
  font-weight: bold;
  display: inline-block;
  left: 20px;
  cursor: pointer;
}

.addbox span {
  font-size: 24px;
}

.textarea:focus {
  outline: none;
}

.flex {
  display: flex;
}

.box {
  margin-top: 120px;
  display: flex;
  justify-content: space-between;
  width: 100%;
  flex-wrap: wrap;
}

.chat-input {
  width: calc(100% - 720px);
  margin-bottom: 70px;
  flex-shrink: 0;
  position: fixed;
  bottom: 32px;
}

.input-wrapper {
  width: calc(100% - 720px);
  background: #fff;
  border-radius: 24px;
  height: 200px;
  padding: 24px 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: fixed;
  bottom: 32px;
}

.model-select {
  min-width: 180px;
  height: 40px !important;
}

:deep() .el-select__wrapper {
  height: 40px !important;
  border-radius: 20px;
  padding-left: 16px;
  padding-right: 16px;
}

/* input {
  flex: 1;
  min-width: 200px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
} */

.action-buttons {
  display: flex;
}

.aaaa {
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
  height: -moz-fit-content;
  height: fit-content;
  width: 100%;
  height: 10px;
  overflow-anchor: none;
}

.btn-default {
  width: 102px;
  height: 40px;
  border-radius: 20px;
  opacity: 1;
  background: #dceafe;
  box-sizing: border-box;
  border: 1px solid #bfdafe;
  font-size: 14px;
  color: #4e6bfe;
  padding: 12px 14px;
  display: flex;
  align-items: center;
  margin-left: 24px;
}

.btn-default img {
  width: 20px;
  height: auto;
  margin-right: 8px;
}

.btn-primary {
  width: 102px;
  height: 40px;
  border-radius: 20px;
  opacity: 1;
  background: #ffffff;
  box-sizing: border-box;
  border: 1px solid #e0e0e0;
  font-size: 14px;
  color: #666666;
  padding: 12px 14px;
  display: flex;
  align-items: center;
  margin-left: 24px;
}

.btn-primary img {
  width: 20px;
  height: auto;
  margin-right: 8px;
}

button:focus {
  outline: none;
}

.tools {
  display: flex;
  align-items: center;
  gap: 24px;
}

.tools-item {
  width: 40px;
  height: 40px;
  border-radius: 20px;
  background: #f3f4f6;
  text-align: center;
  align-items: center;
  display: flex;
  position: relative;
}

.send {
  background: #d5d9ec;
}

.send-checked {
  background-color: #6968de;
}

.tools-item img {
  cursor: pointer;
  font-size: 20px;
  color: #666;
  margin: auto;
}

:deep().el-dialog__footer {
  padding-top: 25px !important;
}

.textarea1 {
  font-size: 16px;
  font-weight: 400;
  font-size: 16px;
  color: #bcbec0;
  border: 0;
  width: calc(100%);
  height: 300px;
  resize: none;
  background: #ffffff;
  border-radius: 12px 12px 12px 12px;
  border: 1px solid #f2f2f2;
  padding: 20px;
  margin-top: 24px;
}

.textarea1:focus {
  outline: none;
}

.features {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  padding: 0 15px;
  align-content: start;
}

.title1 {
  font-size: 20px;
  font-weight: 700;
}

.feature-card {
  background: #fff;
  padding: 60px 30px 30px 30px;
  border-radius: 12px;
  text-align: left;
  height: fit-content;
  position: relative;
}

.footer {
  display: flex;
}

.footer div {
  cursor: pointer;
}

.cancal {
  width: 120px;
  line-height: 40px;
  height: 40px;
  border-radius: 20px;
  background: #fff;
  color: #666666;
  border: 1px solid #999999;
  text-align: center;
  font-size: 14px;
  color: #666666;
  margin-left: 227px;
  margin-right: 16px;
}

.outok {
  width: 120px;
  line-height: 40px;
  height: 40px;
  border-radius: 20px;
  background: #5450cc;
  color: #ffffff;
  text-align: center;
  font-size: 14px;
}

.bg1 {
  background: linear-gradient(160deg, #ddf4f6 5%, #d4f1f2 50%, #c3eaeb);
}

.bg2 {
  background: linear-gradient(160deg, #b9d9f6 3%, #cfe4fb 48%, #b8d9f6 95%);
}

.bg3 {
  background: linear-gradient(160deg, #d2d0f7 3%, #dde0fc 48%, #d2cff7 95%);
}

.feature-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;
  position: absolute;
  left: 13px;
  top: -24px;
}

.feature-icon i {
  font-size: 24px;
}

.feature-card h3 {
  margin-bottom: 10px;
  color: #333;
}

.feature-card p {
  color: #666;
  font-size: 14px;
}

.history-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px 20px 60px 20px;
  position: absolute;
  background: #fff;
  top: -380px;
  right: -180px;
  z-index: 100;
  width: 670px;
  box-shadow: 0px 0px 10px 0px rgba(65, 79, 146, 0.11);
  border-radius: 8px;
  height: 351px;
}

.history-content {
  height: 230px;
  overflow-y: auto;
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* Internet Explorer 10+ */
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.history-header h1 {
  font-family: Alibaba PuHuiTi 2, Alibaba PuHuiTi 20;
  font-weight: 700;
  font-size: 16px;
  color: #333333;
  line-height: 22px;
  text-align: left;
  font-style: normal;
  text-transform: none;
}

:deep().el-input__wrapper {
  padding: 8px 16px;
  border: 0 !important;
  border-radius: 20px;
  width: 180px;
  height: 40px;
  font-size: 14px;
}

:deep().el-input__wrapper:focus {
  outline: none;
}

:deep().el-button {
  outline: none !important;
}

.history-group {
  margin-bottom: 24px;
}

.date-header {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
  text-align: left;
}

.history-item {
  /* display: flex;
  justify-content: space-between; */
  align-items: center;
  padding: 10px 13px;
  border: 1px solid #e0e0e0;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f9fafb;
  border-radius: 4px 4px 4px 4px;
}

.history-item img {
  margin-right: 20px;
  width: 16px;
  height: 16px;
  margin-top: 4px;
}

:deep().el-message {
  z-index: 9999999999 !important;
}

.history-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.item-content {
  flex: 1;
  display: flex;
  justify-content: space-between;
}

.item-text {
  font-family: Alibaba PuHuiTi 2, Alibaba PuHuiTi 20;
  font-weight: 700;
  font-size: 14px;
  color: #333333;
  line-height: 24px;
  text-align: left;
  font-style: normal;
  text-transform: none;
}

.item-time {
  font-family: Alibaba PuHuiTi 2, Alibaba PuHuiTi 20;
  font-weight: 400;
  font-size: 12px;
  color: #999999;
  line-height: 12px;
  text-align: left;
  font-style: normal;
  text-transform: none;
}

.item-actions {
  display: flex;
  justify-content: space-between;
  gap: 8px;
}

.action-btn {
  background: none;
  border: none;
  padding: 4px 8px;
  cursor: pointer;
  color: #666;
  transition: color 0.3s ease;
}

.action-btn:hover {
  color: #1a73e8;
}

.flex-b {
  display: flex;
  justify-content: space-between;
}

:deep().el-dialog__body {
  padding-top: 0;
}

.title1 {
  font-family: Alibaba PuHuiTi 2, Alibaba PuHuiTi 20;
  font-weight: 700;
  font-size: 20px;
  color: #333333;
  line-height: 22px;
  text-align: center;
  font-style: normal;
  text-transform: none;
}

.history-item img {
  margin-right: 20px;
  width: 16px;
  height: 16px;
}

@media (max-width: 1423px) {
  .input-wrapper {
    height: auto;
  }

  .history-container {
    right: -600px;
  }
}

@media (max-width: 768px) {
  .home {
    padding: 15px;
    height: 100%;
  }

  .title {
    font-size: 20px;
    margin-bottom: 30px;
  }

  .input-wrapper {
    flex-direction: column;
    align-items: stretch;
  }

  .history-item img {
    margin-right: 20px;
    width: 16px;
    height: 16px;
  }

  .model-select {
    width: 100%;
  }

  .action-buttons {
    width: 100%;
    justify-content: space-between;
  }

  .tools {
    width: 100%;
    justify-content: space-around;
    margin-left: 0;
  }

  .features {
    grid-template-columns: 1fr;
    margin-bottom: 20px;
  }
}
</style>

<style src="./quest.css"></style>
